package com.xiaode.controller.callBack;

import java.util.Collection;
import java.util.List;
import com.huawei.welink.api.callback.CallBackV1;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.ext.cors.EnableCORS;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xiaode.util.welink.Main;
import com.xiaode.util.welink.WeLinkUtil;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
/**
 * 测试	test	{"encrypt": "xxx"}	{"eventType": "test","timestamp": "1562752619"}
 * 企业信息更改	corpEditTenant	{"encrypt": "xxx"}	{"eventType": "corpEditTenant","timestamp": "1562752619", "tenantId": "xxx"}
 * 人员信息更改	corpEditUser	{"encrypt": "xxx"}	{"eventType": "corpEditUser","timestamp": "1562752619", "data":[{"userId": "id1", "tenantId": "xxx"},{"userId": "id2", "tenantId":"xxx"}]}
 * 人员信息删除	corpDelUser	{"encrypt": "xxx"}	{"eventType": "corpDelUser","timestamp": "1562752619", "data":[{"userId": "id1", "tenantId": "xxx"},{"userId": "id2", "tenantId":"xxx"}]}
 * 部门信息更改	corpEditDept	{"encrypt": "xxx"}	{"eventType": "corpEditDept","timestamp": "1562752619", "data":[{"deptCode": "id1", "tenantId": "xxx"},{"deptCode": "id2", "tenantId":"xxx"}]}
 * 部门信息删除	corpDelDept	{"encrypt": "xxx"}	{"eventType": "corpDelDept","timestamp": "1562752619", "data":[{"deptCode": "id1", "tenantId": "xxx"},{"deptCode": "id2", "tenantId":"xxx"}]}
 *
 * 人员信息变更包括人员新增和人员修改, 部门信息更改包括部门新增和部门修改
 * WeLink仅会通知发生内容变化的用户id或者部门id等，应用需要自行调用相关的查询接口，将接口返回的信息覆盖原来的信息。
 */
@EnableCORS
public class ReturnController extends Controller {
	
	@Inject
	ReturnService service;
	
	static CallBackV1 callBack = null;
	
	@Before(Tx.class)
	public void index() throws Exception{
		String data = HttpKit.readData(getRequest());
		if(StrUtil.isBlank(data)){
			renderNull(); return;
		}
		if(callBack == null) {
			callBack = new CallBackV1(WeLinkUtil.ClientSecret);
		}
		JSONObject rqjson = JSONUtil.parseObj(callBack.decryptRequest(data));
		System.err.println(rqjson);
		if(rqjson.containsKey("code")) {
			renderNull(); return;
		}
	    String eventType = rqjson.getStr("eventType");
	    JSONArray dataArray = rqjson.getJSONArray("data");
	    //人员信息更改
	    if(eventType.equals("corpEditUser")) {
	    	List<String> roleList = Db.query("SELECT role_code FROM wl_role WHERE role_group_code = ? ", "POST");	    	
	    	for(int i = 0; i < dataArray.size(); i++) {
	    		JSONObject jo = (JSONObject) dataArray.get(i);
	    		String userId = jo.getStr("userId");
	    		JSONObject jsonuser = WeLinkUtil.getWLUserInfo(userId);
	    		if(jsonuser == null) {
	    			continue;
	    		}
	    		//判断学生还是老师
	    		JSONArray roleIds = jsonuser.getJSONArray("roleIds");
	    		List<String> roleIdl = roleIds.toList(String.class);
	    		if(roleIdl.contains("R46EDD2B80E7C46B193D956069F14E3D2") || roleIdl.contains("RA42165B48A264CC59A800AAC43261D98")) {//学生
	    			service.editStudent(jsonuser);
	    		}else {//老师
	    			Collection<String> interList = CollUtil.intersection(roleIdl, roleList);
	    			if(interList.size() > 0) {
	    				service.editTeacher(jsonuser);
	    			}
	    		}
	    	}
	    }else if(eventType.equals("corpDelUser")){//人员信息删除
	    	for(int i = 0; i < dataArray.size(); i++) {
	    		JSONObject jo = (JSONObject) dataArray.get(i);
	    		String userId = jo.getStr("userId");
	    		//删除逻辑
	    		service.delUser(userId);
	    	}
		}
		
		//返回
		long time = System.currentTimeMillis() / 1000;
		String respJson = "{\"timestamp\":\""+time+"\",\"msg\":\"success\"}";
		String ivStr2 = Main.createIV(16);
		String respStr = Main.encryptByGcm(respJson, WeLinkUtil.ClientSecret, ivStr2);
	    renderJson("{\"encrypt\":\""+ivStr2+respStr+"\"}");
	}


}
